package com.itkf.core.lifecycle;

import com.itkf.common.StrategyModel.StrategyChoose;
import com.itkf.core.config.DtpProperties;
import com.itkf.core.config.ThreadPoolProperties;
import com.itkf.core.executor.DtpExecutor;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.Set;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
public class DtpRegistry{
    /**
     * 管理线程池的生命
     */
    private static final Map<String, DtpExecutor> REGISTER = new ConcurrentHashMap<>();
    /**
     * 配置类
     */
    private final DtpProperties dtpProperties;

    public DtpRegistry(DtpProperties dtpProperties) {
        this.dtpProperties = dtpProperties;
    }

    /**
     * 注册线程池
     */
    @PostConstruct
    public void init() {
        // 初始化注册所有线程池
        dtpProperties.getExecutors().forEach(config -> {
            DtpExecutor executor = createExecutor(config);
            REGISTER.put(config.getThreadPoolName(), executor);
        });
    }

    /**
     * 获取Map
     */
    public static Map<String, DtpExecutor> getAllExecutor() {
        return REGISTER;
    }

    /**
     * 获取线程池名字
     */
    public static Set<String> getAllExecutorName() {
        return REGISTER.keySet();
    }

    /**
     * 根据线程池名字获取线程池实例
     */
    public static DtpExecutor getDtpExecutor(String threadPoolName) {
        DtpExecutor dtpExecutor = REGISTER.get(threadPoolName);
        if (dtpExecutor == null) {
            log.error("该线程池已失效{}", threadPoolName);
            throw new RuntimeException(threadPoolName);
        }
        return dtpExecutor;
    }


    //TODO 线程池初始化
    private DtpExecutor createExecutor(ThreadPoolProperties config) {
        // 根据队列类型创建阻塞队列
        BlockingQueue<Runnable> workQueue;
        switch (config.getType()) {
            case Priority:
                workQueue = new LinkedBlockingQueue<>(config.getQueueCapacity());
                break;
            case Eager:
                workQueue = new ArrayBlockingQueue<>(config.getQueueCapacity());
                break;
            default:
                throw new IllegalArgumentException("Unsupported queue type: " + config.getType());
        }

        // 创建线程工厂
        ThreadFactory threadFactory = new CustomThreadFactory(config.getThreadPoolName());

        // 创建拒绝策略
        RejectedExecutionHandler handler = (RejectedExecutionHandler) StrategyChoose.choose(config.getRejectedPolicyType());

        return new DtpExecutor(
                config.getCorePoolSize(),
                config.getMaxPoolSize(),
                config.getKeepAliveTime().toMillis(),
                TimeUnit.MILLISECONDS,
                workQueue,
                threadFactory,
                handler);
    }

    // 自定义线程工厂
    private static class CustomThreadFactory implements ThreadFactory {
        private final AtomicInteger threadNumber = new AtomicInteger(1);
        private final String namePrefix;

        CustomThreadFactory(String poolName) {
            namePrefix = "dtp-" + poolName + "-thread-";
        }

        public Thread newThread(Runnable r) {
            Thread t = new Thread(r, namePrefix + threadNumber.getAndIncrement());
            if (t.isDaemon())
                t.setDaemon(false);
            if (t.getPriority() != Thread.NORM_PRIORITY)
                t.setPriority(Thread.NORM_PRIORITY);
            return t;
        }
    }

}
